/***
 * mutex2.c 简化版: 粗粒度锁
 *      只使用了一把锁, 看着简洁了,但是性能肯定有所下降
 * P325-327
 */

#include <stdlib.h>
#include <pthread.h>

#define NHASH 29
#define HASH(id) (((unsigned long int)id) % NHASH)

struct foo
{
    int f_count; /* protected by hashlock */
    pthread_mutex_t f_lock;
    int f_id;
    struct foo *f_next; /* protected by hashlock */
    /* ... more stuff here ... */
};

struct foo *foo_alloc(int id) /* allocate the object */
{
    struct foo *fp;
    int idx;

    if ((fp = malloc(sizeof(struct foo))) != NULL)
    {
        fp->f_count = 1;
        fp->f_id = id;
        if(pthread_mutex_init(&fp->f_lock,NULL) != 0)
        {
            free(fp);
            return (NULL);
        }
    }
}